package demo1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-08-06
 * Time: 16:55
 */


import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class EchoServer {
    private DatagramSocket echoserver = null;

    public EchoServer(int n) throws SocketException {
        echoserver = new DatagramSocket(n);
    }

    public void start() throws IOException {

        System.out.println("服务器启动");
        while (true){
            DatagramPacket resquestPacker = new DatagramPacket(new byte[4096], 4096);
            echoserver.receive(resquestPacker);
            String request = new String(resquestPacker.getData(), 0, resquestPacker.getLength());
            String response = process(request);
            DatagramPacket  responsePacker = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    resquestPacker.getSocketAddress());
            echoserver.send(responsePacker);
            System.out.printf("[%s: %d] req: %s, res: %s\n", resquestPacker.getAddress().toString(), resquestPacker.getPort(),
                    request, response);
        }

    }

    private String process(String str){
        return str;
    }

    public static void main(String[] args) throws IOException {
        EchoServer echoServer = new EchoServer(9090);
        echoServer.start();
    }


}
